package com.bjdd.jdy.ui.commitCard;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bjdd.jdy.R;
import com.bjdd.jdy.base.BaseActivity;
import com.bjdd.jdy.base.BaseResult;
import com.bjdd.jdy.entity.AreaBean;
import com.bjdd.jdy.entity.CityBean;
import com.bjdd.jdy.entity.ProvinceBean;
import com.bjdd.jdy.entity.ToolBean;
import com.bjdd.jdy.util.ImageUtil;
import com.bjdd.jdy.util.L;
import com.bjdd.jdy.util.PopUtil;
import com.bjdd.jdy.util.RxSchedulers;
import com.bjdd.jdy.util.SpUtil;
import com.bjdd.jdy.util.StatusBarUtil;
import com.bjdd.jdy.util.StringUtils;
import com.bjdd.jdy.util.T;
import com.bjdd.jdy.view.widget.PopList;
import com.liuguangqiang.ipicker.IPicker;
import com.lljjcoder.citypickerview.widget.CityPicker;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class CommitCardActivity extends BaseActivity<CommitPresenter, CommitModel> implements CommitContract.View {


    @Bind(R.id.toolbar_back)
    ImageView toolbarBack;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.choose_city)
    TextView chooseCity;
    private static int REQUEST_CODE = 100;
    @Bind(R.id.et_commit_name)
    EditText etName;
    @Bind(R.id.et_commit_cardno)
    EditText etCardno;
    @Bind(R.id.img_idcard_zheng)
    ImageView imgPerson;
    @Bind(R.id.img_idcard_fan)
    ImageView imgPersonCard;
    @Bind(R.id.img_idcard_sc)
    ImageView imgCardFront;
    @Bind(R.id.tc_commit_vehicle)
    TextView tcVehicle;
    @Bind(R.id.cb_commit_agree)
    CheckBox cbAgree;
    @Bind(R.id.tv_commit_agreement)
    TextView tvAgreement;
    @Bind(R.id.tv_toolbar_right)
    TextView tv_commit;
    @Bind(R.id.et_concact)
    EditText etConcact;
    @Bind(R.id.et_concact_mobile)
    EditText etConcactMobile;
    private OptionsPickerView pvOptions;
    //是否勾选同意协议
    private boolean isAgree = true;
    //选择城市数据是否初始化
    private boolean bInitCity = false, bInitVehicle = false;
    private WindowManager.LayoutParams params;
    private PopList pop;
    //照片地址
    private String photo1, photo2, photo3, photo4;
    private final int LINK_MAN_REQUEST_CODE = 0;
    private int CHOOSE_PHOTO = 0;
    private int toolId = -1;
    private int provinceId = -1, cityId = -1, areaId = -1;
    private Map<String, String> data;
    private Map<String, RequestBody> photos;
    ImageUtil imageUtil;

    @Override
    public int getLayoutId() {
        return R.layout.activity_commit_card;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void initView() {
        StatusBarUtil.setColor(this, Color.parseColor("#F9F9F9"), 0);
        /*tv_commit.setText("提交");
        tv_commit.setTextColor(Color.parseColor("#FFDF22"));
        tv_commit.setVisibility(View.VISIBLE);*/
        //初始化城市选择
        initCityPicker();
        //监听checkbox
        initCheckbox();
        initPop();
        //初始化图片选择
        initIPicker();
        imageUtil = new ImageUtil(context);
    }

    @Override
    public void commitSuccess(BaseResult result) {
        imageUtil = null;
        finish();
    }

    @Override
    public void commitFailer(BaseResult result) {

    }

    @Override
    public void setArea(List<ProvinceBean> citys) {
        ArrayList<ArrayList<CityBean>> options2Items = new ArrayList<>();
        ArrayList<ArrayList<ArrayList<AreaBean>>> options3Items = new ArrayList<>();
        for (int i = 0; i < citys.size(); i++) {//遍历省份
            ArrayList<CityBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<AreaBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < citys.get(i).getCities().size(); c++) {//遍历该省份的所有城市
                //String CityName = citys.get(i).getCities().get(c).getCityName();
                CityList.add(citys.get(i).getCities().get(c));//添加城市

                ArrayList<AreaBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (citys.get(i).getCities().get(c).getAreas() == null
                        || citys.get(i).getCities().get(c).getAreas().size() == 0) {
                    City_AreaList.add(new AreaBean());
                } else {

                    for (int d = 0; d < citys.get(i).getCities().get(c).getAreas().size(); d++) {//该城市对应地区所有数据
                        //String AreaName = citys.get(i).getCities().get(c).getAreas().get(d).getAreaName();

                        City_AreaList.add(citys.get(i).getCities().get(c).getAreas().get(d));//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                ProvinceBean provinceBean = citys.get(options1);
                CityBean cityBean = options2Items.get(0).get(options2);
                AreaBean areaBean = options3Items.get(0).get(options2).get(options3);
                provinceId = provinceBean.getProvinceId();
                cityId = cityBean.getCityId();
                areaId = areaBean.getAreaId();
                String tx = provinceBean.getProvinceName() + " " + cityBean.getCityName() + " " + areaBean.getAreaName();
                chooseCity.setText(tx);
                chooseCity.setTextColor(getResources().getColor(R.color.text_black));
            }
        }).build();
        pvOptions.setPicker(citys, options2Items, options3Items);
        bInitCity = true;
    }

    @Override
    public void setTools(List<ToolBean> tools) {
        bInitVehicle = true;
        List<String> data = new ArrayList<>();
        for (int i = 0; i < tools.size(); i++) {
            data.add(tools.get(i).getToolName());
        }
        data.add("清除");
        pop = new PopList(this, data, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String vehicle = data.get(position);
                tcVehicle.setText(vehicle);
                if (TextUtils.equals(vehicle, "清除")) {
                    tcVehicle.setText("请选择交通工具");
                    toolId = -1;
                    tcVehicle.setTextColor(Color.parseColor("#999999"));
                } else {
                    tcVehicle.setTextColor(getResources().getColor(R.color.text_black));
                    toolId = tools.get(position).getToolId();
                }
                pop.dismiss();
            }
        });
        PopUtil.setPop(pop);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBg(1f);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.toolbar_back, R.id.choose_city, R.id.btn_commit,
            R.id.img_idcard_fan, R.id.img_idcard_sc, R.id.img_idcard_zheng, R.id.tc_commit_vehicle, R.id.tv_commit_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_back:
                finish();
                break;
            case R.id.choose_city:
                if (bInitCity) {
                    pvOptions.show();
                } else {
                    T.show("数据初始化未完成");
                }
                break;
            case R.id.img_idcard_zheng:
                //正面
                CHOOSE_PHOTO = 1;
                IPicker.open(context);
                break;
            case R.id.img_idcard_fan:
                //反面
                CHOOSE_PHOTO = 2;
                IPicker.open(context);
                break;
            case R.id.img_idcard_sc:
                //本人手持
                CHOOSE_PHOTO = 3;
                IPicker.open(context);
                break;
            case R.id.tc_commit_vehicle:
                //选择交通工具
                if (bInitVehicle) {
                    setBg(0.7f);
                    pop.showAtLocation(tvAgreement, Gravity.BOTTOM, 0, 0);
                } else {
                    T.show("交通工具数据获取失败");
                }
                break;
            case R.id.tv_commit_agreement:
                //查看自由人协议
                L.d("查看自由人协议");
                break;
            case R.id.btn_commit:
                //提交
                String c = chooseCity.getText().toString();
                if (TextUtils.equals(c, getResources().getString(R.string.city_ts))) {
                    T.show("请先选择城市");
                    return;
                }
                if (TextUtils.isEmpty(etName.getText().toString())) {
                    T.show("姓名不能为空");
                    return;
                }
                if (TextUtils.isEmpty(etCardno.getText().toString())) {
                    T.show("身份证号码不能为空");
                    return;
                }
                if (!StringUtils.isIdCard(etCardno.getText().toString())) {
                    T.show("请检查身份证格式");
                    return;
                }
                if (TextUtils.isEmpty(etConcact.getText().toString())) {
                    T.show("紧急联系人不能为空");
                    return;
                }
                if (TextUtils.isEmpty(etConcactMobile.getText().toString())) {
                    T.show("紧急联系人电话不能为空");
                    return;
                }
                if (TextUtils.isEmpty(photo4) || TextUtils.isEmpty(photo2) || TextUtils.isEmpty(photo3)) {
                    T.show("请确保上传所有所需图片");
                    return;
                }
                if (!isAgree) {
                    T.show("请先阅读并同意协议");
                    return;
                }
                //@Part("photo\";filename=\"image.png\"")RequestBody img
                Map<String, String> params = new HashMap<>();
                photos = new HashMap<>();
                params.put("realName", etName.getText().toString());//真实姓名
                params.put("idCard", etCardno.getText().toString());//身份证号码
                params.put("concact", etConcact.getText().toString());//紧急联系人
                params.put("concactMobile", etConcactMobile.getText().toString());//紧急联系人电话
                params.put("carrierId", SpUtil.getUser().getCarrierId());//用户ID
                if (areaId != -1) {
                    params.put("areaId", areaId + "");
                }
                if (toolId != -1) {
                    params.put("toolId", toolId + "");
                }
                data = params;
                File file2 = new File(photo2);
                compressImg(file2, 0);
                /*RequestBody requestBody2 = RequestBody.create(MediaType.parse("multipart/form-data"), file2);
                File file3 = new File(photo3);
                RequestBody requestBody3 = RequestBody.create(MediaType.parse("multipart/form-data"), file3);
                File file4 = new File(photo4);
                RequestBody requestBody4 = RequestBody.create(MediaType.parse("multipart/form-data"), file4);
                photos.put("personCardPhoto\";filename=\"image.png\"", requestBody4);
                photos.put("frontCardPhoto\";filename=\"image.png\"", requestBody2);
                photos.put("backCardPhoto\";filename=\"image.png\"", requestBody3);
                presenter.commit(SpUtil.getToken(), params, photos);*/
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        L.d("requestCode:" + requestCode + "----resultCode:" + resultCode);
        if (requestCode == LINK_MAN_REQUEST_CODE && data != null) {
            Uri contactUri = data.getData();
            String[] queryFields = new String[]{
                    ContactsContract.Contacts.DISPLAY_NAME,
                    ContactsContract.Contacts._ID
            };
            Cursor c = getContentResolver().query(contactUri, queryFields, null, null, null);
            if (c == null) {
                return;
            }
            if (c.getCount() == 0) {
                return;
            }
            c.moveToFirst();
            String name = c.getString(0);
            L.d("name:" + name);

        }

    }

    /**
     * 初始化城市选择器
     */
    private void initCityPicker() {
        presenter.getArea(SpUtil.getToken());
    }


    /**
     * 初始化chexkbox
     */
    private void initCheckbox() {
        cbAgree.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isAgree = isChecked;
            }
        });
    }

    /**
     * 初始化交通工具弹出框
     */
    private void initPop() {
        //初始化选择交通工具popwindow
        presenter.getTools(SpUtil.getToken());

    }

    /**
     * 初始化图片选择器
     */
    private void initIPicker() {
        IPicker.setLimit(1);
        IPicker.setOnSelectedListener(new IPicker.OnSelectedListener() {
            @Override
            public void onSelected(List<String> paths) {
                L.d("图片选择返回:" + paths.size());
                if (paths.size() > 0) {
                    L.d("图片地址:" + paths.get(0));
                    switch (CHOOSE_PHOTO) {
                        case 1:

                            photo2 = paths.get(0);
                            imageUtil.loadLocalImage(paths.get(0), imgPerson);
                            /*Luban.get(context)
                                    .load(new File(photo2))
                                    .putGear(Luban.THIRD_GEAR)
                                    .setCompressListener(new OnCompressListener() {
                                        @Override
                                        public void onStart() {

                                        }

                                        @Override
                                        public void onSuccess(File file) {

                                        }

                                        @Override
                                        public void onError(Throwable e) {

                                        }
                                    }).launch();*/
                            break;
                        case 2:
                            photo3 = paths.get(0);
                            imageUtil.loadLocalImage(paths.get(0), imgPersonCard);
                            break;
                        case 3:
                            photo4 = paths.get(0);
                            imageUtil.loadLocalImage(paths.get(0), imgCardFront);
                            break;
                    }

                }

            }
        });
    }

    /**
     * 设置背景
     *
     * @param p 透明度
     */
    private void setBg(float p) {
        if (params == null) {
            params = getWindow().getAttributes();
        }
        params.alpha = p;
        getWindow().setAttributes(params);
    }

    private void compressImg(File file, int type) {
        Luban.get(context)
                .load(file)
                .putGear(Luban.THIRD_GEAR)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                        switch (type) {
                            case 0:
                                photos.put("frontCardPhoto\";filename=\"image.png\"", requestBody);
                                File file3 = new File(photo3);
                                compressImg(file3,1);
                                break;
                            case 1:
                                RequestBody requestBody3 = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                                photos.put("backCardPhoto\";filename=\"image.png\"", requestBody3);
                                File file4 = new File(photo4);
                                compressImg(file4,2);
                                break;
                            case 2:
                                photos.put("personCardPhoto\";filename=\"image.png\"", requestBody);
                                presenter.commit(SpUtil.getToken(), data, photos);
                                break;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoadingDialog();
                        T.show(e.getMessage());
                    }
                }).launch();
    }

}
